<template>
  <div class="goodsType">
    <div class="goodsType">
      <div class="accountTop goodsTop">
        <el-button class="defaultBtn" icon="fas fa-caret-right" @click="expanded">折叠全部</el-button>
        <el-button class="defaultBtn" @click="addFirst">新增一级分组</el-button>
      </div>
      <div class="accountBtm">
        <el-tree
          :props="treeProps"
          :data="tableData"
          node-key="id"
          ref="treeType"
          default-expand-all
        >
          <span class="custom-tree-node" slot-scope="{node, data}">
            <span>
              {{ node.label }}
              <img v-if="data.thumb" class="thumb" :src="data.thumb" />
            </span>
            <span>
              <el-button
                type="text"
                v-if="data.level == 1"
                size="mini"
                @click="() => addSecond(node, data)"
                @click.stop
              >新增二级分组</el-button>
              <!-- <el-button
                type="text"
                v-if="data.level == 2"
                size="mini"
                @click="() => addThird(node, data)"
                @click.stop
              >新增三级分组</el-button>-->
              <el-button type="text" size="mini" @click="() => editNode(node, data)" @click.stop>编辑</el-button>
              <el-button
                type="text"
                class="red"
                size="mini"
                @click="() => deleteNode(data)"
                @click.stop
              >删除</el-button>
            </span>
          </span>
        </el-tree>
      </div>
    </div>
    <el-dialog title="修改分组名称" :visible.sync="typeVisible" width="400px" class="adminBox" top="0">
      <el-form label-position="right" label-width="120px" size="medium">
        <el-form-item label="级别">
          <el-radio-group v-model="type.group" disabled>
            <el-radio :label="0">一级</el-radio>
            <el-radio :label="1">二级</el-radio>
            <el-radio :label="2">三级</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="type.group!=0" label="一级分组">
          <el-select disabled v-model="type.second">
            <el-option v-for="item in firstOpt" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="type.group!=0 && type.group==2" label="二级分组">
          <el-select disabled v-model="type.third">
            <el-option v-for="item in secondOpt" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="typeTitle">
          <el-input v-model="type.name"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            :action="action"
            :data="uploadData"
            :show-file-list="false"
            :on-success="specsSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="type.thumb" :src="type.thumb" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="blueBtn mini" @click="submit">确认</el-button>
        <el-button class="defaultBtn mini" @click="typeVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  get_category_list_all,
  edit_category_info,
  del_category_co,
  add_category_info
} from "@/utils/api/market";
import httpRequest from "@/utils/httpRequest";
import { mapState, mapActions } from "vuex";

export default {
  computed: {
    ...mapState({
      company: state => state.company
    })
  },
  data() {
    return {
      tableData: [],
      allTree: [],
      treeData: [],
      action: httpRequest.adornUrl("/market/upload/upload"),
      uploadData: { type: "2" },
      treeProps: { children: "child", label: "name" },
      isexpand: true,
      type: {
        thumb: "",
        group: "",
        name: "",
        second: "",
        third: "",
        parentid: "",
        level: ""
      },
      typeTitle: "一级分组名称",
      typeVisible: false,
      firstOpt: [],
      secondOpt: []
    };
  },
  created() {
    this.queryType();
  },
  methods: {
    //商品分类
    queryType: function() {
      this.$http({
        url: this.$http.newApi("/home/market/goods/get_category_list_all"),
        method: "post",
        data: this.$http.adornData({ coId: this.company.id })
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    },

    getTrees: function(arr, newarr, old, status) {
      var a = this;
      arr.map(item => {
        if (status && item.level !== 1) {
          item.name = old.name + "-" + item.name;
        }
        newarr.push(item);
        if (item.child) {
          a.getTrees(item.child, newarr, item, status);
        }
      });
    },
    resetType: function() {
      this.type = {
        thumb: "",
        group: "",
        name: "",
        second: "",
        third: "",
        parentid: "",
        level: ""
      };
    },
    expanded: function() {
      this.isexpand = !this.isexpand;
      for (
        var i = 0;
        i < this.$refs.treeType.store._getAllNodes().length;
        i++
      ) {
        this.$refs.treeType.store._getAllNodes()[i].expanded = this.isexpand;
      }
    },

    specsSuccess(res, file) {
      if (res.code == 200) {
        this.type.thumb = res.data.file_url;
      } else {
        this.$message.error(res.message);

        return;
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    addFirst: function() {
      this.typeVisible = true;
      this.type.group = 0;
      this.typeTitle = "一级分组名称";
    },
    addSecond: function(node, data) {
      this.typeVisible = true;
      this.type.group = 1;
      this.type.second = data.id;
      this.typeTitle = "二级分组名称";
    },
    addThird: function(node, data) {
      this.typeVisible = true;
      this.type.group = 2;
      this.type.second = node.parent.data.id;
      this.type.third = data.id;
      this.typeTitle = "三级分组名称";
    },
    editNode: function(node, data) {
      console.log(node, data);
      this.typeVisible = true;
      this.typeTitle = "修改分类";
      var second =
        data.level == 1
          ? ""
          : data.level == 2
          ? node.parent.data.id
          : node.parent.parent.data.id;
      var third = data.level == 3 ? node.parent.data.id : "";
      this.type = {
        id: data.id,
        name: data.name,
        thumb: data.thumb,
        group: data.level - 1,
        second: second,
        third: third,
        parentid: data.parentid,
        level: data.level
      };
    },
    deleteNode: function(data) {
      var a = this;
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$http({
            url: this.$http.newApi("/home/market/category/del_category_info"),
            method: "post",
            data: this.$http.adornData({ id: data.id })
          }).then(res => {
            if (res.code == 200) {
              a.queryType();
              a.$message.success("删除分类成功");
            } else {
              a.$message.error(res.message);
            }
          });
        })
        .catch(() => {
          a.$message.info("已取消删除");
        });
    },
    submit: function() {
      if (this.type.id) {
        this.editType();
      } else {
        this.addType();
      }
    },
    addType: function() {
      var a = this,
        parentid = "";
      if (a.type.group == 0) {
        parentid = "";
      } else if (a.type.group == 1) {
        parentid = a.type.second;
      } else {
        parentid = a.type.third;
      }

      this.$http({
        url: this.$http.newApi("/home/market/category/add_category_info"),
        method: "post",
        data: this.$http.adornData({
          name: a.type.name,
          parentId: parentid,
          thumb: a.type.thumb,
          level: a.type.group + 1
        })
      }).then(res => {
        if (res.code == 200) {
          a.queryType();
          a.resetType();
          a.typeVisible = false;
        } else {
          a.$message.error(res.message);
        }
      });
    },
    editType: function() {
      var a = this;

      this.$http({
        url: this.$http.newApi("/home/market/category/edit_category_info"),
        method: "post",
        data: this.$http.adornData({
          id: a.type.id,
          name: a.type.name,
          thumb: a.type.thumb
        })
      }).then(res => {
        if (res.code == 200) {
          a.queryType();
          a.resetType();

          a.typeVisible = false;
        } else {
          a.$message.error(res.message);
        }
      });
    },
    //清空规格表
    clearPrepare: function() {
      var a = this;

      this.$http({
        url: this.$http.adornUrl("/goods/Commodity/delete_prepare_option"),
        method: "post",
        data: this.$http.adornData({})
      }).then(res => {
        if (res.code === 0) {
          a.basicInfo = {
            goodName: "",
            goodSort: "",
            goodAttr: [],
            goodService: [],
            price: "",
            postage: "",
            old_price: "",
            cost_price: "",
            stock: "",
            postageType: 0,
            urlList: [],
            goodContent: "",
            comMethod: 0,
            status: 2,
            imageUrl: []
          };
        } else {
          a.$message.error(res.message);
        }
      });
    },
    tabClick: function(tab) {
      if (tab.name == "goodsRelease") {
        this.clearPrepare();
        this.goodsLabel = "商品发布";
        this.stepActive = 0;
        this.edit = false;
        this.specsShow = false;
      } else {
        this.goodsLabel = "商品发布";
      }
    }
  }
};
</script>

<style>
.thumb {
  width: 30px;
  height: 30px;
  margin-left: 20px;
}
.goodsType .el-tree > .el-tree-node {
  background-color: #fff;
  margin-bottom: 0;
  border-radius: 6px;
}

.goodsType .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.custom-tree-node span {
  display: flex;
  align-items: center;
}

.goodsType .el-tree-node__content {
  height: 54px;
  border-bottom: 1px solid #dfdfdf;
  color: #333;
}

.el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
.avatar {
  width: 40px;
  height: 40px;
  display: block;
}
</style>